<style scoped>
.padding5 {
  padding: 5px;
}
/*.tableScroll {
  overflow: hidden;
}
.ivu-modal-footer {
  display: none;
}*/

</style>
<style>
  /*modal2 隐藏 footer 222*/
/*  .xsa .ivu-modal-wrap .ivu-modal .ivu-modal-content .ivu-modal-footer {
    display: none;
  }*/
</style>

<template>
  <Card>
    <div>
      <Row style="text-align:left;padding:10px 0;">
        <Col span="6">
        <Input v-model="queryStr" placeholder="编号/设备类型/品牌/地址/空间" @on-enter="query(queryStr)">
        </Input>
        </Col>
        <Col span="18" style="text-align:right;">
        <div style="display: inline-flex;width: 600px;" v-if="uploadFile !== null">
          <div style="flex: 5;text-align: right;padding-right: 10px;"> <span style="font-size: 18px;">已选文件:  {{ uploadFile.name }}</span> </div>
          <div style="flex: 1;margin-top: 0px;">
            <Button type="success" @click="doUpload" :loading="upLoadingStatus"> {{upLoadingStatus?'正在上传':'确认上传'}} </Button>
          </div>
        </div>
        <!--<Upload style="display: inline-flex;" :before-upload="beforeDoUpload" action="" accept=".xlsx">-->
          <!--<Button type="info" icon="ios-download-outline" :disabled="upLoadingStatus">选择导入</Button>-->
        <!--</Upload>-->
        <!--<Button type="info" @click="exportData(1)" icon="ios-download-outline">导出</Button>-->
        <Button type="success" icon="ios-add-circle-outline" @click.native="resetEngine()" :loading="loadingReset">重置引擎
        </Button>
        <Button type="success" icon="ios-add-circle-outline" @click.native="add()">新增设备</Button>
        <Button type="success" icon="ios-add-circle-outline" @click.native="add2()">新增虚拟设备</Button>
          <Button type="success" icon="ios-add-circle-outline" @click.native="add3()">新增组合设备</Button>
        <Button type="error" icon="ios-trash-outline" :disabled="deleteMoreDisabled" @click.native="deleteMoreBtn()">删除</Button>
        </Col>
      </Row>
      <Table :loading="spinShow" border :columns="columns7" :data="tableList" ref="table"
             @on-selection-change="tableCheckbox" size="small"></Table>
      <Row style="text-align:right;padding:10px 0;">
        <Page :total="pageObj.total" size="small" show-elevator :page-size="pageObj.size" @on-change="pageChange" @on-page-size-change="pageSizeChange"></Page>
      </Row>
    </div>
    <!--真实设备modal-->
    <Modal v-model="modal1" :title="modalTitle" width="1700" @on-cancel="cancel" @on-ok="ok" :scrollable="true"
           @on-visible-change="modalChangeStatus">
      <Tabs v-model="showTabPanel" type="card">
        <TabPane name="oneTab" label="设备信息" class="padding5">
          <DeviceManageForm ref="refDeviceInfoForm" @showTab="showTab" @saveSubmitReady="saveSubmitReady" @updSubmitReady="updSubmitReady"></DeviceManageForm>
        </TabPane>
        <TabPane name="twoTab" label="采集项" class="padding5">
          <CollectionForm ref="refDeviceColForm" @showTab="showTab" @saveSubmitReady="saveSubmitReady" @updSubmitReady="updSubmitReady"></CollectionForm>
        </TabPane>
        <!--<TabPane name="threeTab" label="阀值设定" class="padding5">
          <LimitSetting ref="limitSetting"></LimitSetting>
        </TabPane>-->
        <TabPane name="fourTab" label="参数设定" class="padding5">
          <DevParams ref="devParams"></DevParams>
        </TabPane>
        <TabPane name="fiveTab" label="脚本代码" class="padding5">
          <ScriptPanel ref="refScript" @sonCallSave="callSonCalls"></ScriptPanel>
        </TabPane>
      </Tabs>
        <div slot="footer" style="text-align: center;">
            <Button type="primary" @click="callSave()" style="width: 300px;" :loading="saveDevLoading">保存</Button>
        </div>
    </Modal>
    <!--虚拟设备弹窗 start-->
    <Modal v-model="modal2" :title="modalTitle2" width="1700" :scrollable="true"
           @on-visible-change="modalChangeStatus2" :mask-closable="false">
      <VirtualPanel ref="virs" @tell-refresh="doSonRefresh"></VirtualPanel>
      <!--<div slot="footer" style="display: none;"></div>-->
      <div slot="footer" style="text-align: center;">
        <Button type="primary" @click="doSaveVirtualObj" style="width: 300px;">保存数据</Button>
      </div>
    </Modal>
    <!--虚拟设备弹窗 end-->
  <!--    组合设备弹窗-->
    <Modal v-model="modal3" :title="modalTitle3" width="1700" :scrollable="true"
           @on-visible-change="modalChangeStatus" class="xsa" :mask-closable="false">
      <GroupDevice ref="groupDevice" @tell-refresh="doSonRefresh"></GroupDevice>
      <div slot="footer" style="display: none;"></div>
    </Modal>
    <!--录入数据弹窗-->
    <Modal v-model="modal4" :title="modalTitle4" width="1700" :scrollable="true"
           @on-visible-change="dataEntryModalChange" class="xsa" :mask-closable="false">
      <DataEntry ref="dataEntry" :into="dataEntryObj"></DataEntry>
      <div slot="footer" style="display: none;"></div>
    </Modal>
  </Card>
</template>
<script>
  import DeviceManageForm from '../manage/DeviceManageForm.vue'
  import CollectionForm from '../manage/CollectionForm.vue'
  import DataEntry from '../manage/DataEntry.vue'
  // import LimitSetting from '../manage/LimitSetting.vue'
  import DevParams from '../manage/DevParams.vue'
  import VirtualPanel from '../manage/VirtualPanel.vue'
  import ScriptPanel from '../type/ScriptPanel.vue'

  import GroupDevice from '../manage/GroupDevice.vue'

  export default {
    components: {
      DeviceManageForm,
      CollectionForm,
      // LimitSetting,
      DevParams,
      VirtualPanel,
      ScriptPanel,
      GroupDevice,
      DataEntry
    },
    data: function () {
      let self = this
      return {
        saveDevLoading: false,
        loadingReset: false,
        editOneData: {},
        dataEntryObj: {}, // 录入设备数据，传入对象
        pageObj: {total: 0, size: 20, index: 0},
        childObj: {},
        showTabPanel: 'oneTab',
        spinShow: true,
        upLoadingStatus: false,
        uploadFile: null,
        tableList: [],
        totalElements: 0,
        queryStr: '',
        modal1: false,
        modal2: false,
        modal3: false,
        modal4: false,
        modalTitle: '',
        modalTitle2: '',
        modalTitle3: '',
        modalTitle4: '录入设备数据',
        columns7: [{
          type: 'selection',
          width: 60,
          fixed: 'left',
          align: 'center',
          render: (h, params) => {
            let txt = ''
            return h('div', [
              h('span', txt)
            ])
          }
        }, {
          title: 'ID',
          key: 'id',
          width: 120,
          fixed: 'left',
          ellipsis: true,
          tooltip: true,
          align: 'center'
        }, {
          title: '类型',
          width: 80,
          fixed: 'left',
          ellipsis: true,
          tooltip: true,
          align: 'center',
          render: (h, params) => {
            let txt = ''
            if (params.row.type === 0) {
              txt = '真实'
            } else if (params.row.type === 1) {
              txt = '虚拟'
            } else {
              txt = '组合'
            }
            return h('div', [
              h('span', txt)
            ])
          }
        }, {
          title: '编号',
          key: 'sn',
          width: 150,
          fixed: 'left',
          ellipsis: true,
          tooltip: true,
          align: 'center'
        }, {
          title: '名称',
          key: 'name',
          ellipsis: true,
          tooltip: true,
          align: 'center'
        }, {
          title: '设备类型',
          key: 'iotDevType',
          align: 'center',
          render: (h, params) => {
            let txt = ''
            if (params.row.iotDevType) {
              txt = params.row.iotDevType.useType
            }
            return h('div', [
              h('span', txt)
            ])
          }
        }, {
          title: '型号',
          key: 'iotDevType',
          align: 'center',
          render: (h, params) => {
            let txt = ''
            if (params.row.iotDevType) {
              txt = params.row.iotDevType.model
            }
            return h('div', [
              h('span', txt)
            ])
          }
        }, {
          title: '品牌',
          key: 'iotDevType',
          align: 'center',
          render: (h, params) => {
            let txt = ''
            if (params.row.iotDevType) {
              txt = params.row.iotDevType.brand
            }
            return h('div', [
              h('span', txt)
            ])
          }
        }, {
          title: '地址',
          key: 'commAddr',
          ellipsis: true,
          tooltip: true,
          align: 'center'
        }, {
          title: '所属空间',
          key: 'temporaryVariable',
          ellipsis: true,
          tooltip: true,
          align: 'center'
          // render: (h, params) => {
          //   let txt = ''
          //   if (params.row.iotSpace) {
          //     txt = params.row.iotSpace.name
          //   }
          //   return h('div', [
          //     h('span', txt)
          //   ])
          // }
        }, {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 180,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  ghost: true,
                  size: 'small',
                  icon: 'ios-create-outline'
                },
                style: {
                  margin: '3px'
                  // color: '#2db7f5'
                },
                on: {
                  click: () => {
                    if (params.row.type === 0) {
                      self.edit(params.row)
                    } else if (params.row.type === 1) {
                      self.$refs.virs.acceptEditData(params.row)
                      self.modal2 = true
                      self.modalTitle2 = '编辑虚拟设备'
                    } else {
                      self.$refs.groupDevice.acceptEditData(params.row)
                      self.modal3 = true
                      self.modalTitle3 = '编辑组合设备'
                    }
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'info',
                  ghost: true,
                  size: 'small',
                  icon: 'ios-trash-outline'
                },
                style: {
                  margin: '3px'
                  // color: '#2db7f5'
                },
                on: {
                  click: () => {
                    this.dataEntryObj = JSON.parse(JSON.stringify(params.row))
                    this.$refs.dataEntry.iotSpaceName = this.dataEntryObj.iotSpace ? this.dataEntryObj.iotSpace.name : ''
                    this.$refs.dataEntry.params.devId = this.dataEntryObj.id
                    // propsSelections
                    if (this.dataEntryObj.type === 0) {
                      this.$refs.dataEntry.propsSelections = this.dataEntryObj.iotDevType.iotCollItems
                    } else if (this.dataEntryObj.type === 1) {
                      this.$refs.dataEntry.propsSelections = this.dataEntryObj.virtualItems
                    }
                    if (this.$refs.dataEntry.propsSelections.length > 0) {
                      this.$refs.dataEntry.params.selectProp = this.$refs.dataEntry.propsSelections[0].name
                      this.$refs.dataEntry.loadDatas()
                    }
                    this.modal4 = true
                    console.info('click', this.dataEntryObj)
                  }
                }
              }, '录入')
            ])
          }
        }],
        tableCheckboxData: [],
        deleteMoreDisabled: true
      }
    },
    created: function () {
      this.list()
    },
    mounted: function () {
    },
    destroyed: function () {
      this.$Message.destroy()
    },
    methods: {
      callSave () {
          // 调用子组件 保存方法
          this.$refs.refDeviceInfoForm.saveDatasToDb('formValidate')
      },
      callSonCalls () {
        // this.$refs.refDeviceInfoForm.handleSubmit22('formValidate')
        this.$refs.refDeviceInfoForm.submitReady()
      },
      doSaveVirtualObj () {
        // 保存或更新虚拟设备数据
        this.$refs.virs.doSave()
      },
      doSonRefresh () {
        this.list()
        this.modal2 = false
        this.modal3 = false
      },
      show: function (index) {
        this.$Modal.info({
          title: '设备信息',
          content: `名称：${this.tableList[index].name}<br>
        IP地址：${this.tableList[index].commAddr}<br>
        状态：${this.tableList[index].debugStat}<br>
        ----设备类型----<br>
        品牌：${this.tableList[index].iotDevType.brand}<br>
        型号：${this.tableList[index].iotDevType.model}<br>
        协议：${this.tableList[index].iotDevType.prol}<br>
        类型：${this.tableList[index].iotDevType.useType}<br>
        读取间隔：${this.tableList[index].iotDevType.readInterval}<br>
        ----设备空间----<br>
        名字：${this.tableList[index].iotSpace.name}<br>
        备注:${this.tableList[index].iotSpace.remark}`
      })
    },
    remove: function (index) {
      this.tableList.splice(index, 1)
    },
    doUpload: function () {
      if (this.uploadFile === null) {
        this.$Message.info('无法获上传的文件')
        return
      }
      let formData = new FormData()
      formData.append('file', this.uploadFile)
      this.upLoadingStatus = true
      window.myapi.upload('iot/dev/import', formData).then(resp => {
        if (resp.status === 200 && resp.data.status === 200) {
          this.$Notice.success({
            title: '操作提示',
            desc: '已成功上传' + resp.data.data + '条数据'
          })
          // 刷新数据
          this.list()
        } else {
          this.$Notice.warning({
            title: '操作提示',
            desc: resp.data.msg
          })
        }
      }).catch(error => {
        this.$Notice.warning({
          title: '操作提示',
          desc: error
        })
      }).finally(() => {
        this.upLoadingStatus = false
      })
    },
    beforeDoUpload: function (file) {
      this.uploadFile = file
      return false
    },
    exportData: function () {
      let self = this
      // 处理为标准格式
      let columns7Tem = [{
        type: 'selection',
        width: 60,
        align: 'center'
      }, {
        type: 'index',
        width: 60,
        align: 'center'
      }, {
        title: '类型',
        key: 'useType',
        align: 'center'
      }, {
        title: '型号',
        key: 'model',
        align: 'center'
      }, {
        title: '编号',
        key: 'id',
        align: 'center'
      }, {
        title: '品牌',
        key: 'brand',
        align: 'center'
      }, {
        title: '所属空间',
        key: 'temporaryVariable',
        align: 'center'
      }, {
        title: '状态',
        key: 'debugStat',
        align: 'center'
      }, {
        title: '操作',
        key: 'action',
        width: 150,
        align: 'center'
      }]
      self.$refs.table.exportCsv({
        filename: '设备管理数据',
        columns: columns7Tem,
        data: self.tableList.map((data, index) => {
          // 数据处理为标准格式
          let tem = JSON.parse(JSON.stringify(data))
          let obj = {
            useType: tem.iotDevType.useType,
            model: tem.iotDevType.model,
            id: tem.id,
            brand: tem.iotDevType.brand,
            name: tem.iotSpace.name,
            debugStat: tem.debugStat
          }
          return obj
        })
      })
    },
    modalShow: function () {
      this.modal1 = true
    },
    modalHide: function () {
      this.modal1 = false
    },
    ok: function () {
      /* this.$Message.info('Clicked ok') */
    },
    cancel: function () {
      /* this.$Message.info('Clicked cancel') */
    },
      dataEntryModalChange: function (status) {
        if (!status) {
          // 退出modal，清空对象
          this.dataEntryObj = {}
          this.$refs.dataEntry.makeDefault()
          this.$refs.dataEntry.params = {
            sTime: '',
            eTime: '',
            selectProp: '',
            page: 0,
            size: 20
          }
        }
      },
    modalChangeStatus: function (status) {
      if (!status) {
        this.showTabPanel = 'oneTab'
        // this.$refs.limitSetting.limitList = []
        this.$refs.devParams.devParamsList = []
        // 清空 代码的填写
        this.$refs.refScript.makeDefault()
        // 清空组合设备
        this.$refs.groupDevice.setAllDefault()
        this.$refs.groupDevice.showTabPanel = 'aTab'
      }
    },
    modalChangeStatus2: function (status) {
      if (!status) {
        this.$refs.virs.setAllDefault()
      } else {
        this.$refs.virs.setDefaultDevType()
      }
    },
    // resetAndSave: function () {
    //   // this.$refs.refScript.doSave('formValidate')
    //   this.$refs.refDeviceInfoForm.handleSubmit22('formValidate')
    //   this.loadingReset3 = true
    //   window.myapi.do_get('/iot/dev/resetDevInfo').then(resp => {
    //     setTimeout(() => {
    //       this.loadingReset3 = false
    //     }, 2222)
    //   })
    // },
    // 数据list
    list: function () {
      let self = this
      let getData = {
        'size': self.pageObj.size,
        'page': self.pageObj.index,
        // 'iotDevType.brand_sn_name_commAddr_iotDevType.useType_iotSpace.name_plike': self.queryStr /* mkAlter */
        'keyword': self.queryStr /* mkAlter */
      }
      self.spinShow = true
      window.myapi.dev_list(getData).then(function (res) {
        self.tableList = []
        if (res.data.status === 200) {
          self.tableList = res.data.data.content
          self.totalElements = res.data.data.totalElements
          self.pageObj.size = res.data.data.size
          self.pageObj.total = res.data.data.totalElements
        } else {
          let msg = res.data.msg ? res.data.msg : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
        }
        self.spinShow = false
      }).catch(function (e) {
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
          self.tableList = []
          self.spinShow = false
        }
      })
    },
    // 第几页
    pageChange: function (index) {
      let self = this
      self.pageObj.index = index - 1
      self.list()
    },
    // 每页显示多少
    pageSizeChange: function (index) {
    },
    // 删除
    deleteOne: function (id) {
      let self = this
      let arr = []
      arr.push(id)
      self.deleteMore(arr)
    },
    // 删除
    deleteMore: function (arr) {
      let self = this
      let postData = arr
      window.myapi.dev_del(postData).then(function (res) {
        if (res.data.status === 200) {
          self.$Message.error('删除数据成功!')
          self.list()
        } else {
          let msg = res.data.msg ? res.data.msg : '删除数据失败!'
          self.$Message.error(msg)
        }
      }).catch(function (e) {
        let msg = e.response.data.message ? e.response.data.message : '删除数据失败!'
        self.$Message.error({ duration: 0, closable: true, content: msg })
      })
    },
    // 查询
    query: function (str) {
      if (str) {
        this.queryStr = str
        this.pageObj.index = 0
      } else {
        this.queryStr = ''
      }
      this.list()
    },
    resetEngine: function () {
      this.loadingReset = true
     window.myapi.do_get('/iot/dev/resetDevInfo').then(resp => {
       setTimeout(() => {
        this.loadingReset = false
       }, 2222)
     })
    },
    // 新增弹框
    add: function () {
      this.modalTitle = '新增真实设备'
      this.modalShow()
      this.resetModalData()
      this.$refs.refDeviceInfoForm.updateFormdata({})
      this.$refs.refDeviceColForm.updateFormdata({})
      this.editOneData = {}
    },
    // 新增虚拟设备
    add2: function () {
      this.$refs.virs.loadDatas()
      this.modal2 = true
      this.modalTitle2 = '新增虚拟设备'
      this.$refs.virs.setAllDefault()
    },
    add3: function () {
      this.$refs.groupDevice.loadDevDatas()
      this.modal3 = true
      this.modalTitle3 = '新增组合设备'
      this.$refs.groupDevice.setAllDefault()
    },
    // 编辑
    edit: function (data) {
      this.modalTitle = '编辑真实设备'
      this.modalShow()
      this.resetModalData()
      // 调用子组件，传值
      this.$refs.refDeviceInfoForm.updateFormdata(data)
      this.$refs.refDeviceColForm.updateFormdata(data)
      this.$refs.refScript.updateFormdata(data)
      // 暂时 注释 阀值设定的功能
      // this.$refs.limitSetting.refreshEditData(data)
      this.$refs.devParams.refreshEditData(data)
      this.editOneData = data
    },
    // 新增
    save5: function () {
      let postData = this.childObj
      // 获取报警数据
      // postData.iotLimits = this.$refs.limitSetting.limitList
      // 获取参数
      postData.devParams = this.$refs.devParams.devParamsList
      // 获取脚本
      postData.scriptSwitch = this.$refs.refScript.scriptObj.switch
      postData.script = this.$refs.refScript.scriptObj.codes === '' ? '' : this.$refs.refScript.scriptObj.codes
        this.saveDevLoading = true
      window.myapi.dev_save(postData).then((res) => {
        if (res.data.status === 200) {
          this.$Message.success('保存成功!')
          this.modalHide()
          this.resetModalData()
          this.pageObj.index = 0
          this.query()
        } else {
          let msg = res.data.msg ? res.data.msg : '保存失败！'
          this.$Message.error(msg)
        }
      }).catch(function (e) {
        let msg = e.response.data.message ? e.response.data.message : '保存失败!'
        this.$Message.error({ duration: 0, closable: true, content: msg })
      }).finally(() => {
          this.saveDevLoading = false
      })
    },
    // 修改
    upd: function () {
      let postData = this.childObj
      // postData.iotLimits = this.$refs.limitSetting.limitList
      postData.devParams = this.$refs.devParams.devParamsList
      // 提取脚本数据
      postData.scriptSwitch = this.$refs.refScript.scriptObj.switch
      postData.script = this.$refs.refScript.scriptObj.codes === '' ? '' : this.$refs.refScript.scriptObj.codes
        this.saveDevLoading = true
      window.myapi.dev_upd(postData).then((res) => {
        if (res.data.status === 200) {
          this.$Message.success('保存成功!')
          this.modalHide()
          this.resetModalData()
          this.query()
        } else {
          let msg = res.data.msg ? res.data.msg : '保存失败！'
          this.$Message.error(msg)
        }
      }).catch(function (e) {
        let msg = e.response.data.message ? e.response.data.message : '保存失败!'
        this.$Message.error({ duration: 0, closable: true, content: msg })
      }).finally(() => {
          this.saveDevLoading = false
      })
    },
    // 显示的tab
    showTab: function (chirldData) {
      let self = this
      if (chirldData.objStr) {
        // 存储form里面的数据
        let obj = JSON.parse(chirldData.objStr)
        self.childObj.name = obj.name
        self.childObj.model = obj.model
        self.childObj.sn = obj.sn
        self.childObj.sort = obj.sort
        self.childObj.commAddr = obj.commAddr
        self.childObj.readInterval = obj.readInterval
        self.childObj.iotSpace = obj.iotSpace
        self.childObj.iotDevType = obj.iotDevType
        self.childObj.iotDevType.iotCollItems.forEach((item) => {
          if (item.isGet === true || item.isGet === 'true') {
            item.isGet = 1
          } else {
            item.isGet = 0
          }
        })
        if (obj.debugStat) {
          self.childObj.debugStat = obj.debugStat
        }
        if (obj.id !== undefined) {
          self.childObj.id = obj.id
        }
      }
      /* if (chirldData.arrStr) {
        // 存储form里面的数据
        self.childObj.iotCollItems = chirldData.arrStr
      } */
      self.showTabPanel = chirldData.tab
    },
    // form弹窗
    updSubmitReady: function () {
      let self = this
      self.upd()
    },
    // form弹窗
    saveSubmitReady: function () {
      let self = this
      self.save5()
    },
    // 初始化弹窗的数据
    resetModalData: function () {
      let self = this
      // document.querySelector('.ivu-modal-footer').style.display = 'none'
      self.childObj = {}
      sessionStorage.manageDeviceInfo = ''
      sessionStorage.manageDeviceCollection = ''
    },
    // tableCheckbox变化
    tableCheckbox: function (selection) {
      let self = this
      self.tableCheckboxData = selection
      if (self.tableCheckboxData.length > 0) {
        self.deleteMoreDisabled = false
      } else {
        self.deleteMoreDisabled = true
      }
    },
    // 多项删除
    deleteMoreBtn: function () {
      let self = this
        this.$Modal.confirm({
            title: '提示',
            content: '<p>您确定删除吗？</p>',
            onOk: () => {
                if (self.tableCheckboxData.length > 0) {
                let arr = []
                self.tableCheckboxData.forEach((item) => {
                  arr.push(item.id)
                })
                self.deleteMore(arr)
              }
            },
            onCancel: () => {
                // this.$Message.info('Clicked cancel')
            }
        })
    }
  }
}

</script>
